package com.reny.ll.git.base_logic.ext

import com.reny.ll.git.base_logic.MApp
import com.reny.ll.git.base_logic.config.LOGIN_INFO
import com.reny.ll.git.base_logic.config.RConfig
import com.reny.ll.git.base_logic.model.login.LoginInfo

fun Any.checkLogin(nextFunc: (() -> Unit)? = null, tip:String = ""){
    if(isLogin()){
        nextFunc?.let {
            it()
        }
    }else {
        clearUser()
        toast(tip)
        jumpLogin()
    }
}

fun Any.jumpLogin(index: Int = 0){
    router().build(RConfig.FtLogin.login)
        .withInt("index", index)
        .navigation()
}

fun Any.clearUser(){
    kv().removeValueForKey(LOGIN_INFO)
    //kv().removeValueForKey(USER_INFO)
    MApp.loginInfo = null
    //MApp.userInfo = null
    //LogoutEvent().postEvent()
}

fun Any.isLogin():Boolean = getLoginInfo() != null

/*fun Any.getUser(): UserInfo?{
    if(!isLogin()){
        clearUser()
        return null
    }
    if(MApp.userInfo != null){
        return MApp.userInfo
    }
    try {
        MApp.userInfo = kv().decodeParcelable(USER_INFO, UserInfo::class.java, null)
    }catch (e:Exception){
        MApp.userInfo = null
        clearUser()
    }

    return MApp.userInfo
}*/

fun Any.getLoginInfo(): LoginInfo?{
    if(MApp.loginInfo != null){
        return MApp.loginInfo
    }
    MApp.loginInfo = kv().decodeParcelable(LOGIN_INFO, LoginInfo::class.java, null)
    //loge("read loginINfo?: ${gson.toJson(MApp.loginInfo)}  ${MApp.loginInfo == null}")
    return MApp.loginInfo
}

fun Any.authorization():String?{
    if(isLogin()){
        return getLoginInfo()!!.token_type + " " + getLoginInfo()!!.access_token
    }
    return null
}
